import BScroll from '@better-scroll/core'
import PullUp from '@better-scroll/pull-up'
// import ObserveDOM from '@better-scroll/slide'
import ObserveDOM from '@better-scroll/observe-dom'
import { ref, onMounted, onUnmounted, onDeactivated, onActivated } from 'vue'

BScroll.use(PullUp)
BScroll.use(ObserveDOM)

export default function usePullUpLoad(requestData, preventPullUpLoad) {
    const scroll = ref(null)
    const rootRef = ref(null)
    const isPullUpLoad = ref(false) // 判断拉去是否结束

    onMounted(() => {
        const scrollVal = scroll.value = new BScroll(rootRef.value, {
            pullUpLoad: true,
            observeDOM: true,
            click: true
        })
        scrollVal.on('pullingUp', pullingUpHandler)

        async function pullingUpHandler() {
            if (preventPullUpLoad.value) {
                scrollVal.finishPullUp()
                return
            }
            isPullUpLoad.value = true
            await requestData()
            scrollVal.finishPullUp() // 告诉 better-scroll 上拉结束
            scrollVal.refresh()
            isPullUpLoad.value = false
        }
    })

    onUnmounted(() => {
        scroll.value.destroy()
    })
    onActivated(() => {
        scroll.value.enable()
        scroll.value.refresh()
    })

    onDeactivated(() => {
        scroll.value.disable()
    })
    return {
        scroll,
        rootRef,
        isPullUpLoad
    }
}
